<?php
header("Content-Type: application/json; charset=UTF-8");
require_once 'db.php';

try {
    // 验证参数
    $userId = filter_input(INPUT_GET, 'user_id', FILTER_VALIDATE_INT);
    $coachId = filter_input(INPUT_GET, 'coach_id', FILTER_VALIDATE_INT);

    if (!$userId || !$coachId || $userId < 1 || $coachId < 1) {
        throw new Exception("参数不合法");
    }

    // 准备查询语句
    $stmt = $conn->prepare("
        SELECT COUNT(*) AS valid_count 
        FROM bookings 
        WHERE user_id = ? 
          AND coach_id = ?
          AND status IN (1, 2)
    ");
    
    if (!$stmt) {
        throw new Exception("数据库查询准备失败: " . $conn->error);
    }

    $stmt->bind_param("ii", $userId, $coachId);
    $stmt->execute();
    
    // 获取结果
    $result = $stmt->get_result();
    $row = $result->fetch_assoc();
    
    echo json_encode([
        'status' => 'success',
        'hasBooking' => $row['valid_count'] > 0
    ]);

} catch (Exception $e) {
    error_log("Check Booking Error: " . $e->getMessage());
    http_response_code(400);
    echo json_encode([
        'status' => 'error',
        'msg' => $e->getMessage()
    ]);
} finally {
    if (isset($stmt)) $stmt->close();
    $conn->close();
}
?>